package com.demo.key.server

import com.demo.key.listeners.IConnectTimeListener
import com.demo.key.util.transConnectTime
import kotlinx.coroutines.*

object ConnectTime0822Manager {
    private var connectTime=0L
    private var countJob:Job?=null
    private val listenerList= arrayListOf<IConnectTimeListener>()

    fun resetConnectTime(){
        connectTime=0L
    }

    fun startCountTime(){
        countJob= GlobalScope.launch(Dispatchers.Main) {
            while (true){
                listenerList.forEach { it.connectTimeListener(transConnectTime(connectTime)) }
                connectTime++
                delay(1000L)
            }
        }
    }

    fun stopCountTime(){
        connectTime=0L
        countJob?.cancel()
        countJob=null
    }

    fun addTimeListener(call:IConnectTimeListener){
        if (!listenerList.contains(call)){
            listenerList.add(call)
        }
    }

    fun deleteTimeListener(call:IConnectTimeListener){
        if (listenerList.contains(call)){
            listenerList.remove(call)
        }
    }
}